/*
 * @Author: wangtao
 * @Date: 2020-12-18 09:14:01
 * @LastEditors: 汪滔
 * @LastEditTime: 2021-06-03 18:47:53
 * @Description: 配置合同
 */
import React, { Component } from 'react';
import {
  StyleSheet,
  View,
  PixelRatio,
  SafeAreaView,
  DeviceEventEmitter,
  TouchableOpacity,
  Image,
} from 'react-native';
import Pdf from 'react-native-pdf';
import { msg, Button, XMHeader, BackImageOn } from '@/common';
import {
  mainBgColorWhite,
  px2dp,
  screenHeight,
  screenWidth,
  splitLineColorLightGray,
} from '@/styles';
import { iconChainGray } from '@/images';
import api from '@/api';
import ContractSign from './contract-sign';

const { Submit } = Button;

export default class ContractContent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      contractSignIsShow: false,
      contractData: {},
      custId: '',
    };
  }

  componentDidMount() {
    this.getUserInfo();
    const { contractData } = this.props;
    if (
      !contractData &&
      JSON.stringify(contractData) == '{}' &&
      (!contractData.contractUrl || !contractData.compoundFileUrl)
    ) {
      msg.emit('app:tip', { text: '合同链接错误，请重试' });
      msg.emit('router: back');
    }
  }

  render() {
    const { contractStatus, contractData, routerFrom } = this.props;
    const { contractSignIsShow } = this.state;
    return (
      <SafeAreaView>
        <View style={styles.container}>
          <XMHeader
            title='合同详情'
            renderLeft={() => {
              return (
                <BackImageOn onClick={() => {
                  this.handleBackButtonAction();
                }}
                />

              );
            }}
            renderRight={() => {}}
          />
          {/* 这里嵌入合同 */}
          <Pdf
            source={{ uri: contractData && (contractData.contractUrl || contractData.compoundFileUrl) }}
            onLoadComplete={(numberOfPages, filePath) => {
              console.log(`number of pages: ${numberOfPages}`);
            }}
            onPageChanged={(page, numberOfPages) => {
              console.log(`current page: ${page}`);
            }}
            onError={(error) => {
              console.log(error);
            }}
            onPressLink={(uri) => {
              console.log(`Link presse: ${uri}`);
            }}
            style={[styles.pdf, contractStatus === 4 ? { paddingBottom: px2dp(0) } : null]}
          />
          {
            contractStatus !== 4 &&
            <View style={styles.bottomBox}>
              <Submit
                text='同意并签署合同'
                boxStyle={styles.boxStyle}
                btnStyle={{}}
                btnTextStyle={{
                  fontSize: px2dp(36),
                }}
                onClick={() => {
                  this.setState({ contractSignIsShow: true });
                }}
              />
            </View>
          }
          {/* 签署弹框 */}
          {contractSignIsShow &&
            <ContractSign
              onChange={this.onChange}
              contractData={contractData}
              routerFrom={routerFrom}
              {...this.props}
            />}
        </View>
      </SafeAreaView>
    );
  }

  // 查询用户信息
  getUserInfo() {
    api.user.getUserInfo().then((res) => {
      if (res.success && res.data) {
        if (res.data.avatarId) {
          this.setState({
            custId: res.data.custId,
          });
        }
      }
    });
  }

  // 检查是否授权，已经授权不用发短信
  checkIsContractAuth = () => {
    const { contractData, routerFrom } = this.props;
    const { custId } = this.state;
    const param = {
      custId: custId,
      userType: 1,
      contractNo: contractData.contractNo,
    };
    api.contract.isContractAuth(param).then((res) => {
      if (res.success) {
        if (res.data == true) {
          // 已经授权走签署页面
          msg.emit('router: goToNext', {
            routeName: 'ContractAutograph',
            routerFrom,
            data: contractData,
            instId: contractData.instanceId || contractData.id,
          });
        } else {
          // 未授权
          this.setState({ contractSignIsShow: true });
        }
      }
    });
  };

  // 处理返回按钮
  handleBackButtonAction = () => {
    const { contractStatus, contractData, routerFrom } = this.props;
    if (routerFrom == 'B2BMallOrderPay') {
      // msg.emit('checkContractDone', contractData)
      DeviceEventEmitter.emit('checkContractDone', contractData);
    }
    msg.emit('router: back');
  };

  // 改变
  onChange = (type, val) => {
    this.setState({ [type]: val });
  };

  // 查看哈希值
  checkHashcode = () => {
    const { contractData } = this.props;
    const hashCode = contractData && contractData.hashCode;
    msg.emit('app:messageBox', {
      isVisible: true,
      title: '合同已完成在小马区块链上的安全存证',
      text: '存证哈希值',
      secText: `${hashCode}`,
      okText: '我知道了',
      okFn: () => {
        msg.emit('app:messageBox', { isVisible: false });
      },
    });
  };

  // 检查是否授权，已经授权不用发短信
  checkIsContractAuth = () => {
    const { contractData } = this.props;
    const param = {
      custId: contractData.buyerId,
      userType: contractData.buyerType,
      contractNo: contractData.contractNo,
    };
    api.contract.isContractAuth(param).then((res) => {
      if (res.success) {
        if (res.data == true) {
          // 已经授权走签署页面
          this.submitB2BContract();
        } else {
          // 未授权
          this.setState({ contractSignIsShow: true });
        }
      }
    });
  };

  // b2b提交
  submitB2BContract = () => {
    const { contractData, routerFrom } = this.props;
    // this.cancel();
    // msg.emit('app:selfTip', {
    //   isVisible: true,
    //   text: '合同签署中...',
    //   icon: 'loading',
    //   style: {zIndex:1}
    // });
    if (routerFrom == 'B2BMallOrderPay') {
      // b2b合同
      if (contractData.buyerType == 1) {
        msg.emit('router: goToNext', {
          routeName: 'ContractAutograph',
          routerFrom,
          data: contractData,
          instId: contractData.instanceId || contractData.id,
        });
      } else {
        // b2b 上传合同
        const contractParams = {
          instId: contractData.instanceId,
          refId: contractData.buyerId,
          refType: contractData.buyerType,
        };
        api.contract
          .b2bSignPersonContract(contractParams)
          .then((res) => {
            if (res.success) {
              const newData = Object.assign(res.data, data);
              msg.emit('router: goToNext', {
                routeName: 'ContractFeedBack',
                data: newData,
                routerFrom,
              });
            } else {
              msg.emit('app:tip', { text: res.msg });
            }
          })
          .catch((res) => {
            msg.emit('app:tip', { text: '网络错误' });
          });
      }
    }
  };
}
const styles = StyleSheet.create({
  container: {
    backgroundColor: mainBgColorWhite,
    height: '100%',
    width: '100%',
  },
  bottomBox: {
    width: screenWidth,
    height: px2dp(165),
    alignItems: 'center',
    borderTopColor: splitLineColorLightGray,
    borderTopWidth: 1 / PixelRatio.get(),
    position: 'absolute',
    bottom: 0,
    backgroundColor: mainBgColorWhite,
  },
  pdf: {
    flex: 1,
    width: '100%',
    height: screenHeight,
    backgroundColor: mainBgColorWhite,
    paddingBottom: px2dp(165),
  },
  boxStyle: {
    width: px2dp(640),
    height: px2dp(88),
    borderRadius: px2dp(44),
    overflow: 'hidden',
    marginTop: px2dp(10),
  },
  iconGray: {
    width: px2dp(38),
    height: px2dp(38),
  },
});
